<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import TaskColumn from './components/TaskColumn.vue'
import TaskCard from './components/TaskCard.vue'
import CreateTaskDialog from './components/CreateTaskDialog.vue'
import Summary from './components/Summary.vue'
import Timeline from './components/Timeline.vue'

// 定义任务状态
const TASK_STATUS = {
  TODO: '待做',
  DRAFTING: '进行中',
  IN_REVIEW: '审核中',
  DONE: '完成'
}

// 确认弹框相关状态
const showConfirmDialog = ref(false)
const pendingTaskChange = ref<{
  taskId: string,
  newStatus: string
} | null>(null)

// 修改任务相关状态
const showEditDialog = ref(false)
const editingTask = ref<{
  id: string
  title: string
  content: string
  status: string
  assignee: {
    id: number
    avatar: string
    name: string
  }
  dueDate: string
  progress: number
  priority: string
}>()

// 创建任务相关状态
const showCreateDialog = ref(false)

// 定义任务列表
const tasks = ref([
  {
    id: 'TBT-12',
    title: 'Present prototype for final leadership review',
    content: '准备项目原型演示文档，包括功能说明、技术架构和实现方案等内容，并在领导层评审会议上进行展示。',
    status: TASK_STATUS.TODO,
    assignee: {
      id: 1,
      avatar: 'https://example.com/avatar1.jpg',
      name: 'John'
    },
    dueDate: '2025-02-02',
    progress: 0,
    priority: 'high'
  },
  {
    id: 'TBT-18',
    title: 'Build clean energy prototype',
    content: '开发清洁能源原型系统，重点关注能源效率优化和环境友好性，确保符合可持续发展要求。',
    status: TASK_STATUS.TODO,
    assignee: {
      id: 2,
      avatar: 'https://example.com/avatar2.jpg',
      name: 'Sarah'
    },
    dueDate: '2024-08-28',
    progress: 0.5,
    priority: 'medium'
  },
  {
    id: 'TBT-6',
    title: 'Demo AI capabilities to team',
    content: '向团队展示人工智能功能，包括机器学习模型的训练过程、预测准确率和实际应用场景。',
    status: TASK_STATUS.DRAFTING,
    assignee: {
      id: 3,
      avatar: 'https://example.com/avatar3.jpg',
      name: 'Mike'
    },
    progress: 0.3
  },
  {
    id: 'TBT-3',
    title: 'Approve environmental requirements',
    content: '审核并确认环境要求文档，确保所有开发和部署流程符合环保标准。',
    status: TASK_STATUS.IN_REVIEW,
    assignee: {
      id: 4,
      avatar: 'https://example.com/avatar4.jpg',
      name: 'Lisa'
    },
    progress: 0.5
  }
])

// 日期筛选
const dateRange = ref<[Date, Date]>([
  new Date(new Date().setHours(0, 0, 0, 0)), // 今天开始
  new Date(new Date().setDate(new Date().getDate() + 7)) // 7天后
])

// 当前视图
const currentView = ref('summary')

// 处理任务拖拽
const handleTaskDrop = (taskId: string, newStatus: string) => {
  pendingTaskChange.value = {
    taskId,
    newStatus
  }
  showConfirmDialog.value = true
}

// 确认状态变更
const confirmStatusChange = () => {
  if (!pendingTaskChange.value) return
  
  const { taskId, newStatus } = pendingTaskChange.value
  const task = tasks.value.find(t => t.id === taskId)
  if (task) {
    task.status = newStatus
    ElMessage.success('任务状态更新成功')
  }
  showConfirmDialog.value = false
  pendingTaskChange.value = null
}

// 取消状态变更
const cancelStatusChange = () => {
  showConfirmDialog.value = false
  pendingTaskChange.value = null
}

// 获取特定状态的任务（增加日期筛选）
const getTasksByStatus = (status: string) => {
  return tasks.value.filter(task => {
    const taskDate = task.dueDate ? new Date(task.dueDate) : null
    return task.status === status && 
           (!dateRange.value[0] || !dateRange.value[1] || !taskDate || 
           (taskDate >= dateRange.value[0] && taskDate <= dateRange.value[1]))
  })
}

// 创建新任务
const createTask = () => {
  showCreateDialog.value = true
}

// 处理任务创建
const handleTaskCreate = (task: any) => {
  tasks.value.push(task)
  ElMessage.success('任务创建成功')
  showCreateDialog.value = false
}

// 处理修改任务
const handleEditTask = (task: any) => {
  editingTask.value = { 
    id: task.id,
    title: task.title,
    content: task.content || '',
    status: task.status,
    assignee: task.assignee || {
      id: 0,
      avatar: '',
      name: ''
    },
    dueDate: task.dueDate || '',
    progress: task.progress || 0,
    priority: task.priority || 'medium'
  }
  showEditDialog.value = true
}

// 确认修改任务
const confirmEditTask = () => {
  if (!editingTask.value) return
  
  const taskIndex = tasks.value.findIndex(t => t.id === editingTask.value?.id)
  if (taskIndex !== -1) {
    const updatedTask = {
      ...tasks.value[taskIndex],
      ...editingTask.value
    }
    tasks.value[taskIndex] = updatedTask
    ElMessage.success('任务修改成功')
  }
  showEditDialog.value = false
  editingTask.value = undefined
}

// 取消修改任务
const cancelEditTask = () => {
  showEditDialog.value = false
  editingTask.value = undefined
}
</script>

<template>
  <div class="task-container">
    <!-- 顶部导航 -->
    <div class="task-header">
      <div class="nav-tabs">
        <div 
          class="nav-item" 
          :class="{ active: currentView === 'summary' }"
          @click="currentView = 'summary'"
        >
          Summary
        </div>
        <div class="nav-item">Board</div>
        <div class="nav-item">List</div>
        <div class="nav-item">Calendar</div>
        <div 
          class="nav-item"
          :class="{ active: currentView === 'timeline' }"
          @click="currentView = 'timeline'"
        >
          Timeline
        </div>
        <div class="nav-item">Approvals</div>
        <div class="nav-item">Forms</div>
        <div class="nav-item">Pages</div>
        <div class="nav-item">Issues</div>
        <div class="nav-item">Reports</div>
      </div>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="[
            {
              text: '最近一周',
              value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                return [start, end]
              }
            },
            {
              text: '最近一月',
              value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                return [start, end]
              }
            },
            {
              text: '最近三月',
              value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                return [start, end]
              }
            }
          ]"
          class="date-picker"
        />
        <el-button type="primary" @click="createTask">
          <i class="el-icon-plus"></i> 创建任务
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <component
      :is="currentView === 'summary' ? Summary : Timeline"
      :tasks="tasks"
      :task-status="TASK_STATUS"
      :date-range="dateRange"
      @task-drop="handleTaskDrop"
      @edit-task="handleEditTask"
    />

    <!-- 确认弹框 -->
    <el-dialog
      v-model="showConfirmDialog"
      title="确认状态变更"
      width="30%"
    >
      <span>确定要将任务状态变更为 {{ pendingTaskChange?.newStatus }} 吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelStatusChange">取消</el-button>
          <el-button type="primary" @click="confirmStatusChange">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改任务弹框 -->
    <el-dialog
      v-model="showEditDialog"
      title="修改任务"
      width="50%"
    >
      <el-form v-if="editingTask" :model="editingTask" label-width="100px">
        <el-form-item label="任务标题">
          <el-input v-model="editingTask.title" />
        </el-form-item>
        <el-form-item label="任务内容">
          <el-input
            v-model="editingTask.content"
            type="textarea"
            :rows="4"
            placeholder="请输入任务详细内容"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editingTask.status">
            <el-option
              v-for="status in Object.values(TASK_STATUS)"
              :key="status"
              :label="status"
              :value="status"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="editingTask.priority">
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="进度">
          <el-slider
            v-model="editingTask.progress"
            :step="0.1"
            :max="1"
            :format-tooltip="(val) => Math.round(val * 100) + '%'"
          />
        </el-form-item>
        <el-form-item label="截止日期">
          <el-date-picker
            v-model="editingTask.dueDate"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEditTask">取消</el-button>
          <el-button type="primary" @click="confirmEditTask">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 创建任务弹框 -->
    <CreateTaskDialog
      v-model:visible="showCreateDialog"
      :task-status="TASK_STATUS"
      @create="handleTaskCreate"
    />
  </div>
</template>

<style scoped>
.task-container {
  padding: 20px;
  height: 100vh;
  background-color: #f5f7fa;
}

.task-header {
  background: white;
  padding: 16px 24px;
  border-radius: 8px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.nav-tabs {
  display: flex;
  gap: 24px;
}

.nav-item {
  padding: 8px 16px;
  cursor: pointer;
  color: #606266;
  border-radius: 4px;
  transition: all 0.3s;
}

.nav-item:hover {
  color: #409eff;
  background: #ecf5ff;
}

.nav-item.active {
  color: #409eff;
  background: #ecf5ff;
  font-weight: 500;
}

.task-board {
  display: flex;
  gap: 24px;
  padding: 20px;
  overflow-x: auto;
  min-height: calc(100vh - 200px);
  width: 100%;
  align-items: stretch;
}

.task-board > :deep(.task-column) {
  flex: 0 0 calc(25% - 18px);
  min-width: 280px;
  height: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.header-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.date-picker {
  width: 360px;
}
</style> 